package com.retrofit.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetworkConnectChangedReceiver extends BroadcastReceiver {

    private NetEvevt evevt;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
            //获取联网状态的NetworkInfo对象
            NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            if (info != null) {
                //如果当前的网络连接成功并且网络连接可用
                if (NetworkInfo.State.CONNECTED == info.getState() && info.isAvailable()) {
                    if (info.getType() == ConnectivityManager.TYPE_WIFI || info.getType() == ConnectivityManager.TYPE_MOBILE) {
//                        LogUtils.log( getConnectionType(info.getType()) + "连上");
                        if (evevt != null) {
                            evevt.onNetChange(0);
                        }

                    }
                } else {
//                    LogUtils.log( getConnectionType(info.getType()) + "断开");
                    if (evevt != null) {
                        evevt.onNetChange(1);
                    }

                }
            }
        }
    }

    /**
     * 获取连接类型
     *
     * @param type
     * @return
     */
    private String getConnectionType(int type) {
        String connType = "";
        if (type == ConnectivityManager.TYPE_MOBILE) {
            connType = "移动数据";
        } else if (type == ConnectivityManager.TYPE_WIFI) {
            connType = "WIFI网络";
        }
        return connType;
    }

    // 自定义接口
    public interface NetEvevt {
        public void onNetChange(int netMobile);
    }

}